package meb

import (
	"context"
	_ "embed"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/mosongcc/gotool/gjson"
	"github.com/mosongcc/gotool/gtime"
	"github.com/wechatpay-apiv3/wechatpay-go/core"
	"github.com/wechatpay-apiv3/wechatpay-go/services/payments/jsapi"
	"html/template"
	"strings"
	"vitepress-serve/internal/model"
)

//微信扫码支付确认页面，手机与电脑都用这个页面。
//微信点击直接跳转，电脑扫码进入。
//需要在微信支付安全域名目录打开此页面，比如：https://wxpay.mosong.cc/vpapi/meb/pay/:order_id

//go:embed pay_page.html
var pageHtml string

var pageHtmlTpl = template.Must(template.New("page").Parse(pageHtml))

const PATH_PAY_PAGE = "/vpapi/meb/pay/:order_id"

func getPathPayPage(orderId string) string {
	return strings.ReplaceAll(PATH_PAY_PAGE, ":order_id", orderId)
}

// PayPage 支付界面
func (ctl *Controller) PayPage(ctx *gin.Context) (err error) {
	var (
		orderId  = ctx.Param("order_id")
		isWechat = strings.Contains(strings.ToLower(ctx.Request.UserAgent()), "micromessenger") //是否是微信访问 true=是 false=否
	)

	var order model.Order
	if err = ctl.db.Where("order_id = ?", orderId).Take(&order).Error; err != nil {
		return
	}
	if order.Status != model.ORDER_UNPAID {
		err = errors.New("订单当前状态不能继续支付")
		return
	}

	//****** 微信支付 ******
	var (
		payinfo string
		mchid   string
		mchName string
		amt     = fmt.Sprintf("%.2f", float64(order.TxnAmt)/100) //元，两位小数
		title   = order.ProdName
		errMsg  string
	)
	if isWechat {
		var (
			wx    = ctl.ConfigService.Wechat()
			zf    = ctl.ConfigService.Wxpay()
			appid = wx.Appid
		)
		mchid = zf.Mchid
		mchName = zf.MchName

		var uo model.UserOauth
		if err = ctl.db.Where("uid = ? and appid = ?", order.Uid, appid).Take(&uo).Error; err != nil {
			errMsg = "用户不存在"
			return
		}
		var openid = uo.Openid

		var jsapiService *jsapi.JsapiApiService
		jsapiService, err = ctl.WxpayService.Jsapi()
		if err != nil {
			errMsg = err.Error()
			return
		}
		var resp *jsapi.PrepayWithRequestPaymentResponse
		resp, _, err = jsapiService.PrepayWithRequestPayment(context.Background(), jsapi.PrepayRequest{
			Appid:         core.String(appid),
			Mchid:         core.String(mchid),
			Description:   core.String(order.ProdName),
			OutTradeNo:    core.String(order.OrderId),
			TimeExpire:    core.Time(gtime.ParseT14(order.PayTimeout)),
			Attach:        core.String(""),
			NotifyUrl:     core.String(safeNotifyUrl(zf.SafeUrl, mchid, order.OrderId)),
			GoodsTag:      core.String(""),
			LimitPay:      []string{},
			SupportFapiao: core.Bool(false),
			Amount:        &jsapi.Amount{Total: core.Int64(int64(order.TxnAmt))},
			Payer:         &jsapi.Payer{Openid: core.String(openid)},
			SettleInfo:    &jsapi.SettleInfo{ProfitSharing: core.Bool(false)},
		})
		if err != nil {
			errMsg = err.Error()
			return
		}
		payinfo = gjson.MarshalString(resp)
	}

	var host string
	if hostAny := ctl.cache.Get(ctxHostKey + order.Uid); hostAny != nil {
		host = hostAny.(string)
	}
	if host == "" {
		host = "blog.mosong.cc"
	}

	// 页面数据
	var data = map[string]string{
		"title":   title,
		"amt":     amt,
		"mchName": mchName,
		"payinfo": payinfo,
		"errMsg":  errMsg,
		"cbUrl":   fmt.Sprintf("https://%s", host),
	}
	if err = pageHtmlTpl.Execute(ctx.Writer, data); err != nil {
		return
	}
	ctx.Header("Content-Type", "text/html; charset=utf-8")
	return
}

func safeNotifyUrl(safeUrl, mchid, orderId string) string {
	if safeUrl[len(safeUrl)-1:] == "/" {
		safeUrl = safeUrl[:len(safeUrl)-1]
	}
	notifyUrl := safeUrl + PATH_WXPAY_NOTIFY
	notifyUrl = strings.ReplaceAll(notifyUrl, ":mchid", mchid)
	notifyUrl = strings.ReplaceAll(notifyUrl, ":order_id", orderId)
	return notifyUrl
}
